package com.niit.service.impl;

import com.niit.bean.R;
import com.niit.dao.UserRepository;
import com.niit.entity.User;
import com.niit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;// 将dao层的接口UserRepository注入到service中

    //获取全部的用户数据
    public R getUserList() {
        return R.ok().data("data",userRepository.findAll());
    }
    //根据id获取一个用户
    public R getUser(User user) {
        User optionalUser = userRepository.findUserByUsername(user.getUsername());
        if (optionalUser == null){
            return R.error().message("该用户不存在");
        }
        if (!optionalUser.getPassword().equals(user.getPassword())) { // 密码不相等
            return R.error().message("该用户名密码错误~");
        }
        return R.ok().data("data",optionalUser);
    }
    //增加一个用户
    public R addNewUser(User user) {
        User userFromDB = userRepository.findUserByUsernameAndPassword(user.getUsername(),user.getPassword());
        if (userFromDB != null){
            return R.error().message("该用户已存在");
        }
        User newUser = userRepository.save(user);
        if (newUser == null){
            return R.error().message("添加用户失败~");
        }
        return R.ok().message("添加用户成功~");
    }
    //更新用户
    public R updateUser(User user) {
        user.setUpdateTime(new Date()); //设置更新时间
        return R.ok().data("data",userRepository.save(user));
    }
    //删除用户
    public R deleteUser(String username) {
        userRepository.deleteUserByUsername(username);
        return R.ok().message("删除用户成功~");
    }
}
